package com.shjn.squirrel.fragment;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.shjn.squirrel.R;
import com.shjn.squirrel.application.MyApplication;
import com.shjn.squirrel.bean.httpBean.ParamBean;
import com.shjn.squirrel.bean.storageBean.WastePrice;
import com.shjn.squirrel.model.Constant;
import com.shjn.squirrel.model.LocalStorage;
import com.shjn.squirrel.model.UserInfoCache;
import com.shjn.squirrel.utils.MeasureScreenUtils;
import com.shjn.squirrel.utils.SoundPlayUtils;
import com.shjn.squirrel.utils.TimeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * 用户选择垃圾种类（首页）
 */
public class UserSelectFragment extends BaseFragment implements View.OnClickListener {

    private static UserSelectFragment instance;
    private CountDownTimer mCountDownTimer;
    //大件回收、投递指引、垃圾选择按钮
    private Button mBigPiece;
    private Button mGuide;
    private ImageButton mBottle;
    private ImageButton mPaper;
    private ImageButton mBook;
    private ImageButton mPlastic;
    private ImageButton mFabric;
    private ImageButton mMetal;
    private ImageButton mGlass;
    private ImageButton mHarm;
    //垃圾价格
    private TextView mBottlePrice;
    private TextView mPaperPrice;
    private TextView mBookPrice;
    private TextView mPlasticPrice;
    private TextView mFabricPrice;
    private TextView mMetalPrice;
    private TextView mGlassPrice;
    private TextView mHarmPrice;
    private ArrayList<WastePrice> mWastePrice;
    //满箱状态
    private TextView mFullWarningBottle;
    private TextView mFullWarningBook;
    private TextView mFullWarningPaper;
    private TextView mFullWarningPlastic;
    private TextView mFullWarningFabric;
    private TextView mFullWarningMetal;
    private TextView mFullWarningGlass;
    private TextView mFullWarningHarm;

    public UserSelectFragment() {
    }

    public synchronized static UserSelectFragment getInstance() {
        if (instance == null) {
            instance = new UserSelectFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return createView(inflater, R.layout.user_select_garbage, container);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initDownTimer();
        initView();


    }

    /**
     * 初始化倒计时
     */
    private void initDownTimer() {
        if (UserInfoCache.loginState) {
            //倒计时60秒，返回投递结束
            mCountDownTimer = new MyCountDownTimer(60 * 1000 + 1050, 1000);
        } else {
            //倒计时120秒，返回待机页
            mCountDownTimer = new MyCountDownTimer(120 * 1000 + 1050, 1000);
        }
        mCountDownTimer.start();
    }

    /**
     * 初始化相关控件
     */
    private void initView() {
        mBigPiece = (Button) mView.findViewById(R.id.btn_big_piece);
        mGuide = (Button) mView.findViewById(R.id.btn_guide);
        mBottle = (ImageButton) mView.findViewById(R.id.imBtn_bottle);
        mPaper = (ImageButton) mView.findViewById(R.id.imBtn_paper);
        mBook = (ImageButton) mView.findViewById(R.id.imBtn_book);
        mPlastic = (ImageButton) mView.findViewById(R.id.imBtn_plastic);
        mFabric = (ImageButton) mView.findViewById(R.id.imBtn_fabric);
        mMetal = (ImageButton) mView.findViewById(R.id.imBtn_metal);
        mGlass = (ImageButton) mView.findViewById(R.id.imBtn_glass);
        mHarm = (ImageButton) mView.findViewById(R.id.imBtn_harm);
        mBottlePrice = (TextView) mView.findViewById(R.id.tv_bottle_price);
        mPaperPrice = (TextView) mView.findViewById(R.id.tv_paper_price);
        mBookPrice = (TextView) mView.findViewById(R.id.tv_book_price);
        mPlasticPrice = (TextView) mView.findViewById(R.id.tv_plastic_price);
        mFabricPrice = (TextView) mView.findViewById(R.id.tv_fabric_price);
        mMetalPrice = (TextView) mView.findViewById(R.id.tv_metal_price);
        mGlassPrice = (TextView) mView.findViewById(R.id.tv_glass_price);
        mHarmPrice = (TextView) mView.findViewById(R.id.tv_harm_price);
        mFullWarningBottle = (TextView) mView.findViewById(R.id.full_warning_bottle);
        mFullWarningPaper = (TextView) mView.findViewById(R.id.full_warning_paper);
        mFullWarningBook = (TextView) mView.findViewById(R.id.full_warning_book);
        mFullWarningPlastic = (TextView) mView.findViewById(R.id.full_warning_plastic);
        mFullWarningFabric = (TextView) mView.findViewById(R.id.full_warning_fabric);
        mFullWarningMetal = (TextView) mView.findViewById(R.id.full_warning_metal);
        mFullWarningGlass = (TextView) mView.findViewById(R.id.full_warning_glass);
        mFullWarningHarm = (TextView) mView.findViewById(R.id.full_warning_harm);
        mBigPiece.setOnClickListener(this);
        mGuide.setOnClickListener(this);
        mBottle.setOnClickListener(this);
        mPaper.setOnClickListener(this);
        mBook.setOnClickListener(this);
        mPlastic.setOnClickListener(this);
        mFabric.setOnClickListener(this);
        mMetal.setOnClickListener(this);
        mGlass.setOnClickListener(this);
        mHarm.setOnClickListener(this);
        //设置垃圾价格
        mWastePrice = LocalStorage.getWastePrice(MyApplication.getInstance());
        mBottlePrice.setText(String.format("%.2f", mWastePrice.get(0).getUserPrice()) + "元/个");
        mPaperPrice.setText(String.format("%.2f", mWastePrice.get(1).getUserPrice()) + "元/公斤");
        mBookPrice.setText(String.format("%.2f", mWastePrice.get(2).getUserPrice()) + "元/公斤");
        mPlasticPrice.setText(String.format("%.2f", mWastePrice.get(3).getUserPrice()) + "元/公斤");
        mFabricPrice.setText(String.format("%.2f", mWastePrice.get(4).getUserPrice()) + "元/公斤");
        mMetalPrice.setText(String.format("%.2f", mWastePrice.get(5).getUserPrice()) + "元/公斤");
        mGlassPrice.setText(String.format("%.0f", mWastePrice.get(6).getUserPrice()) + "积分/次");
        mHarmPrice.setText(String.format("%.0f", mWastePrice.get(7).getUserPrice()) + "积分/次");
        EventBus.getDefault().register(this);
        //设置垃圾满箱状态
//        mActivity.serialPortUtils.sendSerialPort("androidC56:1;");//发起分类桶状态上报
    }

    /**
     * 分类桶状态上报通知
     *
     * @param canState
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ArrayList<ParamBean> canState) {
        mFullWarningBottle.setVisibility(LocalStorage.getBottleState(MyApplication.getInstance()).getCanFullStatus() == 2 ? View.VISIBLE : View.INVISIBLE);
        mFullWarningPaper.setVisibility(canState.get(1).getCanFullStatus() == 2 ? View.VISIBLE : View.INVISIBLE);
        mFullWarningBook.setVisibility(canState.get(2).getCanFullStatus() == 2 ? View.VISIBLE : View.INVISIBLE);
        mFullWarningPlastic.setVisibility(canState.get(3).getCanFullStatus() == 2 ? View.VISIBLE : View.INVISIBLE);
        mFullWarningFabric.setVisibility(canState.get(4).getCanFullStatus() == 2 ? View.VISIBLE : View.INVISIBLE);
        mFullWarningMetal.setVisibility(canState.get(5).getCanFullStatus() == 2 ? View.VISIBLE : View.INVISIBLE);
        mFullWarningGlass.setVisibility(canState.get(6).getCanFullStatus() == 2 ? View.VISIBLE : View.INVISIBLE);
        mFullWarningHarm.setVisibility(canState.get(7).getCanFullStatus() == 2 ? View.VISIBLE : View.INVISIBLE);
    }

    @Override
    public void onClick(View view) {
        if (!BigRecoveryFragment.getInstance().isAdded() && !DeliverGuideFragment.getInstance().isAdded() &&
                !UserScanFragment.getInstance().isAdded() &&
                !UserOpenDeliverFragment.getInstance().isAdded() &&
                !WarningDialog.getInstance().isAdded()) {
            switch (view.getId()) {
                //大件回收
                case R.id.btn_big_piece:
                    mActivity.mBackAndTimer.setY(287 * MeasureScreenUtils.getDensity(mActivity));
                    TopFragment.getInstance().mBtnMyRecycler.setVisibility(View.INVISIBLE);
                    mActivity.getFragmentManager().beginTransaction()
                            .remove(UserSelectFragment.getInstance())
                            .remove(BottomFragment.getInstance())
                            .replace(R.id.big_piece, BigRecoveryFragment.getInstance())
                            .commit();
                    break;
                //投递指引
                case R.id.btn_guide:
                    TopFragment.getInstance().mBtnMyRecycler.setVisibility(View.INVISIBLE);
                    mActivity.getFragmentManager().beginTransaction()
                            .replace(R.id.mid, DeliverGuideFragment.getInstance())
                            .commit();
                    break;
                case R.id.imBtn_bottle:
                    UserInfoCache.category = Constant.bottle;
                    break;
                case R.id.imBtn_paper:
                    UserInfoCache.category = Constant.paper;
                    break;
                case R.id.imBtn_book:
                    UserInfoCache.category = Constant.book;
                    break;
                case R.id.imBtn_plastic:
                    UserInfoCache.category = Constant.plastic;
                    break;
                case R.id.imBtn_fabric:
                    UserInfoCache.category = Constant.fabric;
                    break;
                case R.id.imBtn_metal:
                    UserInfoCache.category = Constant.metal;
                    break;
                case R.id.imBtn_glass:
                    UserInfoCache.category = Constant.glass;
                    break;
                case R.id.imBtn_harm:
                    UserInfoCache.category = Constant.harm;
                    break;
                default:
                    break;
            }
            //用户选择垃圾种类后，执行以下操作
            if (view.getId() != R.id.btn_big_piece && view.getId() != R.id.btn_guide) {
                //判断此时是否为用户可投递时间
                if (TimeUtils.hourMinuteBetween(new SimpleDateFormat("HH:mm").format(new Date()), Constant.startTime, Constant.endTime)) {
                    //判断是否满箱
                    int fullState = 0;
                    if (UserInfoCache.category.equals(Constant.bottle)) {
                        fullState = LocalStorage.getBottleState(MyApplication.getInstance()).getCanFullStatus();
                    } else {
                        fullState = LocalStorage.getCanState(MyApplication.getInstance()).get(Constant.categoryMap.get(UserInfoCache.category)[3] - 1).getCanFullStatus();
                    }
                    if (fullState != 2) {
                        TopFragment.getInstance().mBtnMyRecycler.setVisibility(View.INVISIBLE);
                        //判断用户是否登录过
                        if (UserInfoCache.loginState) {
                            //跳转到开箱页面
                            if (view.getId() == R.id.imBtn_bottle) {
                                SoundPlayUtils.play(17);//饮料瓶投递语音提示
                            } else {
                                SoundPlayUtils.play(13);//其它种类垃圾开箱语音投递
                            }
                            //打开投口
//                            mActivity.serialPortUtils.sendSerialPort("androidC51:" + Constant.numberMap.get(Constant.categoryMap.get(UserInfoCache.category)[3]) + ";");
                            mActivity.getFragmentManager().beginTransaction()
                                    .replace(R.id.mid, UserOpenDeliverFragment.getInstance())
                                    .commit();
                        } else {
                            //跳转到扫码登录页
                            SoundPlayUtils.play(11);//扫码或手机号语音提示
                            mActivity.getFragmentManager().beginTransaction()
                                    .replace(R.id.mid, UserScanFragment.getInstance())
                                    .commit();
                        }
                    } else {
                        //弹出满桶提示
                        WarningDialog.getInstance()
                                .setMessage("投递箱暂满,请稍后投递哦")
                                .setOnCloseDialogListener(null)
                                .show(mActivity.getFragmentManager(), "box_full_tip");
                    }
                } else {
                    //弹出未在可投递时间提示
                    WarningDialog.getInstance()
                            .setMessage("投递时间为" + Constant.startTime + "-" +  Constant.endTime + "哦~")
                            .setOnCloseDialogListener(null)
                            .show(mActivity.getFragmentManager(), "user_time_tip");
                }
            }

        }

    }

    /**
     * 倒计时器类
     */
    private class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long time) {
            int now = (int) time / 1000 - 1;
            if (now == 0) {
                if (UserInfoCache.loginState) {
                    //返回投递结束页
                    if (WarningDialog.getInstance().isAdded()) {
                        WarningDialog.getInstance().closeDialog();
                    }
                    SoundPlayUtils.play(16);//感谢使用提示音
                    mActivity.getFragmentManager().beginTransaction()
                            .replace(R.id.mid, UserFinishFragment.getInstance())
                            .commit();
                } else {
                    //返回待机页
                    if (WarningDialog.getInstance().isAdded()) {
                        WarningDialog.getInstance().closeDialog();
                    }
                    mActivity.getFragmentManager().beginTransaction()
                            .remove(TopFragment.getInstance())
                            .remove(UserSelectFragment.getInstance())
                            .remove(BottomFragment.getInstance())
                            .replace(R.id.boot, AdvFragment.getInstance())
                            .commit();
                }
            }
        }

        @Override
        public void onFinish() {

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        EventBus.getDefault().unregister(this);
    }
}
